<template>
  <view class="container">
    <view class="page-wrapper">
      <view class="agent-list" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20rpx;">
        <view 
          class="agent-item" 
          v-for="item in items" 
          :key="item.id"
          :style="{ 
            backgroundImage: `url(${item.image_url})`,
            height: '380rpx',
            borderRadius: '5%'
          }"
            @click="showPaymentDialog(item)"
        >
          <view class="content-overlay" style="display: flex; flex-direction: column; justify-content: flex-end; height: 100%; padding-bottom: 10px; background: linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 50%, transparent 100%);">
            <text class="agent-name">{{ item.name || item.title }}</text>
            <text class="agent-info">{{ item.description || '暂无描述' }}</text>
            <view class="btn-wrapper">
              <button class="buy-btn optimized" @click.stop="handleBuy(item)">
                <text class="btn-text" v-if="!item.is_purchased">立即购买</text>
                <text class="btn-text purchased" v-else>已购买</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
 <payment-dialog
      ref="paymentDialogref"
      :qrcode-url="currentQrcode"
      :wechat-nickname="wechatNickname"
      @confirm="handlePaymentSuccess"
    />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import PaymentDialog from '@/components/PaymentDialog.vue';
import { useUserStore } from '@/stores/userdata';


const API_BASE_URL = 'https://yinlihupo.cn';
const items = ref([]);
const loading = ref(false);

// 弹框
const currentQrcode = ref('')
const wechatNickname = ref('开发者昵称') // 替换为实际微信昵称
const paymentDialogref = ref(null)

// 显示支付弹窗
const showPaymentDialog = (item) => {
  currentQrcode.value = item.qrcode
  paymentDialogref.value.openDialog()
}

// 支付成功处理
const handlePaymentSuccess = () => {
  uni.showToast({
    title: '支付成功',
    icon: 'success'
  })
}


// 检查用户登录状态
const isUserLoggedInAndBoundPhone = () => {
  const userStore = useUserStore();
  return !!userStore.access_token && !!userStore.phone;
};

// 加载商品数据
const loadProducts = async () => {
  loading.value = true;
  console.log('[关键节点] 开始加载商品数据');
  
  try {
    // 1. 获取商品列表
    const productsRes = await uni.request({
      url: `${API_BASE_URL}/products/`,
      method: 'GET'
    });
    
    if (productsRes.statusCode === 200 && Array.isArray(productsRes.data)) {
      console.log('[商品数据]', productsRes.data);
      items.value = productsRes.data.map(product => ({
        ...product,
        id: product.product_id,
        image_url: product.image_url || 'https://images.unsplash.com/photo-1620712943543-bcc4688e7485?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80',
        is_purchased: false
      }));
      
      // 2. 检查购买状态
      if (isUserLoggedInAndBoundPhone()) {
        const userStore = useUserStore();
        await Promise.all(items.value.map(async (item) => {
          try {
            const checkRes = await uni.request({
              url: `${API_BASE_URL}/product-check/?product_id=${item.id}&phone=${userStore.phone}`,
              method: 'GET',
              header: {
                'Authorization': `Bearer ${userStore.access_token}`
              }
            });
            
            if (checkRes.statusCode === 200) {
              item.is_purchased = checkRes.data?.exists || false;
            }
          } catch (err) {
            console.error('检查购买状态失败:', err);
          }
        }));
      }
    }
  } catch (err) {
    console.error('[错误] 加载商品失败:', err);
    uni.showToast({ title: '获取商品失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 购买按钮点击事件
const handleBuy = (index) => {
  const product = items.value[index];
  console.log('[购买商品]', product);
  
  if (!isUserLoggedInAndBoundPhone()) {
    uni.showModal({
      title: '操作确认',
      content: '请先登录并绑定手机号后才能继续操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/views/my/login' });
        }
      }
    });
    return;
  }
  
  // 打开支付对话框
  paymentDialog.value.open();
};

// 初始化加载
onMounted(() => {
  loadProducts();
});
</script>

<style scoped>
/* 容器样式 */
.container {
  padding: 24rpx;
  background: 
    linear-gradient(135deg, #0a0e17 0%, #1a1f2e 100%),
    repeating-linear-gradient(
      45deg,
      rgba(56, 182, 255, 0.05) 0px,
      rgba(56, 182, 255, 0.05) 2px,
      transparent 2px,
      transparent 4px
    );
  min-height: 100vh;
  color: #e0e0e0;
}

/* 商品卡片 */
.card {
  background: rgba(255, 255, 255, 0.08);
  border-radius: 16rpx;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(56, 182, 255, 0.2);
  box-shadow: 
    0 0 15px rgba(56, 182, 255, 0.1),
    inset 0 0 10px rgba(56, 182, 255, 0.05);
  transition: all 0.3s ease;
  min-height: 240rpx;
}

.card:active {
  transform: translateY(4rpx);
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

/* 文字内容区域 */
.content {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.title {
  font-size: 34rpx;
  font-weight: 600;
  color: #38b6ff;
  margin-bottom: 12rpx;
  position: relative;
  padding-left: 20rpx;
  text-shadow: 0 0 5px rgba(56, 182, 255, 0.3);
}

.title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 24rpx;
  background: linear-gradient(to bottom, #38b6ff, #00e5ff);
  border-radius: 4rpx;
  box-shadow: 0 0 5px rgba(56, 182, 255, 0.5);
}

.status {
  font-size: 26rpx;
  color: #00e5ff;
  background: rgba(56, 182, 255, 0.15);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  display: inline-block;
  width: fit-content;
  border: 1px solid rgba(56, 182, 255, 0.3);
  animation: pulse 2s infinite;
}

/* 购买按钮 */
.buy-btn {
  background: #0b405e;
  color: #fff;
  border: none;
  border-radius: 30rpx;
 padding-top: 8px;
 padding-bottom: 8px;
  font-size: 22rpx;
  line-height: 1.2;
  margin-top: 10rpx;
  box-shadow: 0 0 10px rgba(11, 64, 94, 0.3);
  transition: all 0.3s ease;
  align-self: center;
  text-shadow: 0 0 5px rgba(11, 64, 94, 0.5);
  width: 60%;
  margin-bottom: 5px;
}

/* 按钮点击效果 */
.buy-btn:active {
  transform: scale(0.96);
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.5);
}

.card:hover {
  border-color: rgba(56, 182, 255, 0.4);
  box-shadow: 
    0 0 25px rgba(56, 182, 255, 0.2),
    inset 0 0 15px rgba(56, 182, 255, 0.1);
}

/* 加载动画 */
@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.loading-item {
  animation: pulse 1.5s infinite;
}
</style>
